package cake.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import cake.dao.UserDao;
import cake.dao.impl.UserDaoImpl;
import cake.entity.User;
@WebServlet("/admin/userlist")
public class AdminUserListServlet extends HttpServlet{
	
	private UserDao userDao=new UserDaoImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		List<User> users=new ArrayList<User>();
		Gson gson=new Gson();
		String keyWord="";
		if (!req.getParameter("keyWord").isEmpty()) {
			keyWord=req.getParameter("keyWord");
			users=userDao.getUsersByKeyWord(keyWord);
		}else {
			users=userDao.getAll();
		}
		resp.getWriter().print(gson.toJson(users));
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		String uname="";
		if (req.getParameter("uname")!=null) {
			uname=req.getParameter("uname");
			User user=userDao.fetchUserByUserName(uname);
			user.setStatus(!user.isStatus());
			userDao.updateUserStatus(user);
		}
	}
}
